package com.atguigu.guli.service.oss.schdule;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/*
定时任务
 */
@Component
public class OssTask {
    @Autowired
    FileService fileService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Scheduled(cron = "0 0/1 * * *  *")
    public void delTeacherAvatars(){
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps("teacher:delfail:avatars");
        //System.out.println("定时方法被执行.....");
        //如果redis里没有删除失败的头像则结束定时任务
        if (hashOps==null || hashOps.size()==0){
            return;
        }
        //如果存在删除失败的头像 执行定时删除任务
        Map<String, String> entries = hashOps.entries();
        //Set<String> keys = hashOps.keys();
        entries.forEach((path,module)->{
            try {
                //删除头像
                fileService.deleteFile(path,module);
                hashOps.delete(path);
            } catch (Exception e) {
                throw new GuliException(ResultCodeEnum.FILE_DELETE_ERROR,e);
            }
        });

    }
}
